import { getCurrentUser, setCurrentUser, setCurrentAgencies } from '@/utils/common'
import tools from '@/utils/tools'
import $axios from '@/utils/axios'
import api from "@/api";

const user = {
  state: {
    token: getCurrentUser() ? getCurrentUser().token : null,
    centerId: getCurrentUser() ? getCurrentUser().defaultCenterId : null,
    currentAgencyId: getCurrentUser() ? getCurrentUser().currentAgencyId : null,
    uid: getCurrentUser() ? getCurrentUser().userId : null,
    currentUser: getCurrentUser(),
    language: tools.localItem('NG_TRANSLATE_LANG_KEY'),
    currentRole: {},
    viewSource: ''
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_VIEW_SOURCE: (state, viewSource) => {
      state.viewSource = viewSource
    },
    SET_CURRENTUSER: (state, info) => {
      state.currentUser = info
    },
    SET_LANGUAGE: (state, lang) => {
      state.currentUser.language = lang
      state.language = lang
    },
    SET_CENTER_ID: (state, id) => {
      state.centerId = id
    },
    SET_UID: (state, id) => {
      state.uid = id
    },
    SET_CURRENTROLE: (state, obj) => {
      state.currentRole = obj
    }
  },
  actions: {
// 更新设置用户信息
    setCurrentUserAction ({ commit }, user) {
      commit('SET_CURRENTUSER', user)
      setCurrentUser(user)
    },
    // 用户名登录
    loginByUsernameAction ({ dispatch, commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        $axios.post(api.urls().login,{ account: username ,password: userInfo.password, loginType: 'PASSWORD' })
            .then(response => {
              // 存储token、uid、centerId
              commit('SET_TOKEN', response.token)
              commit('SET_UID', response.userId)
              commit('SET_CENTER_ID', response.defaultCenterId || '')
              // 存储用户信息
              dispatch('setCurrentUserAction',response)
              // 用户是否退出
              tools.sessionItem('USER_SIGN_OUT',false)
              resolve()
            }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    getUserInfoAction ({ dispatch,commit, state }) {
      let userInfo = state.currentUser
      return new Promise((resolve, reject) => {
        // store里面没有存储时,否则返回store数据
        if (!userInfo) {
          let cookie = getCurrentUser()
          if (!cookie || cookie.toString().trim() == '') {
            let error = {
              message: 'cookie 不存在'
            }
            reject(error)
          } else {
            try {
              // 如果有 cookie set userinfo
              let _temp = JSON.parse(cookie.toString().trim())
              dispatch('setCurrentUserAction',_temp)
              resolve(_temp)
            } catch (e) {
              // console.log(e, '第一个 try catch')
              try {
                let _temp = JSON.parse(cookie)
                dispatch('setCurrentUserAction',_temp)
                resolve(_temp)
              } catch (e) {
                // console.log(e, '第二个 try catch')
                // 如果失败返回 报错
                reject(e)
              }
            }
          }
        } else {
          resolve(userInfo)
        }
      })
    },
    // 设置用户当前语言
    setLanguageAction ({ commit, state }, lang) {
      // return new Promise((resolve, reject) => {
      //   $axios.post(api.urls().language,{ language: lang })
      //       .then(response => {
      //         // 更新语言
      //         commit('SET_LANGUAGE',lang)
      //         // 更新cookie
      //         let user = state.currentUser
      //         user.language = lang
      //         setCurrentUser(user)
      //         resolve(response)
      //       }).catch(error => {
      //     reject(error)
      //   })
      // })
    },
    // 当前用户功能权限
    setCurrentRoleAction ({ commit }, obj) {
      commit('SET_CURRENTROLE', obj)
    }
  }
}

export default user
